package com.wxtf.platform.plugins.permissions;

import java.util.*;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wxtf.platform.interfaces.CommonsCallProvider;
import com.wxtf.platform.plugins.user.UserBean;
import com.wxtf.platform.supers.LogicBase;
import com.wxtf.platform.tools.AccessDataBaseUtil;
import com.wxtf.platform.tools.ConstantInfoHelper;

/**
 * <li>Title: PermissionsAction.java</li>
 * <li>Project: baseplatform</li>
 * <li>Package: com.wxtf.platform.plugins.permissions</li>
 * <li>Description: 权限点管理-菜单</li>
 * <li>Copyright: Copyright (c) 2012</li>
 * <li>Company: wxthtf Technologies </li>
 * <li>Created on Jul 10, 2012 9:40:12 AM</li>
 *
 * @author chun_chang
 * @version 1.0.0.0
 *
 */
public class PermissionsAction  extends LogicBase implements CommonsCallProvider {
	private static Log log = LogFactory.getLog(PermissionsAction.class);
	private static int _width = 200;
		
	public PermissionsAction(String jsonArray){
		
	}
	@Override
	public Object onInit(Object jsonArray) {
		return null;
	}

	@Override
	public Object onCreate(Object jsonArray) {
		return null;
	}

	@Override
	public Object onDestory(Object jsonArray) {
		return null;
	}

	@Override
	public Object run() {
		Object msg = "";
		try {
			if ("queryPage".equals(this.getMethodName())) {//菜单树
				msg = this.select(this.getExtendData());
			} else if ("save".equals(this.getMethodName())) {//添加
				msg = this.insert(this.getLogicData());
			} else if ("update".equals(this.getMethodName())) {//修改
				msg = this.update(this.getLogicData());
			} else if ("delete".equals(this.getMethodName())) {//删除
				msg = this.delete(this.getLogicData());
			} else if ("listMenu".equals(this.getMethodName())) {//用户权限列表
				msg = this.listTree4User(this.getLogicData());
			} else if ("menuTree".equals(this.getMethodName())) {//角色权限列表
				msg = this.listTree4Role(this.getLogicData());
			} else if ("loadMenu4Left1".equals(this.getMethodName())) {//登录后页面顶部菜单栏-所有菜单
				msg = this.loadMenu4Left1(this.getLogicData());
			} else if ("loadMenu4Left".equals(this.getMethodName())) {//登录后页面左侧菜单树-菜单类别提取
				msg = this.loadMenu4Left(this.getLogicData());
			} else {
				msg = "\"没有【" + this.getMethodName() + "】该方法\"";
			}
			if(msg == null || "[null]".equals(msg)){
				msg = "\"\"";
			}
			if(msg.toString().startsWith("{") || msg.toString().startsWith("[")) {
				return msg.toString();
			}
			msg = ConstantInfoHelper.generateJSONString(msg.toString());
		} catch (Exception e) {
			msg = "操作失败，请联系管理员";
			msg = ConstantInfoHelper.generateJSONString( ConstantInfoHelper.JSON_HEAD, ConstantInfoHelper.getFailResultDetail(msg.toString()), false);
			log.error(e, e);
		} finally {
			this.clear();
		}
		return msg.toString();
	}

	/** 
	 * 描述：select 菜单树列表-一次性列出所有菜单
	 * @param jsonArray
	 * @return
	 * @CreateOn Jul 10, 2012  10:34:35 AM
	 * @author chun_chang
	 */
	@Override
	public Object select(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String pId = jsonObject.getString("id");
		
		List<Map<String, Object>> list = AccessDataBaseUtil.query4ListMap(fields, sql, new Object[] { pId });
		list = this.getMenuByPid(list);
		String msg = "";
		String rootNode = "\"id\":\"0\", \"pparent_id\":\"0\", \"text\":\"菜单根节点\", \"logic_code\":\"\", \"action\":\"\", \"showorder\":\"\",\"icons\":\"\",\"isQuick\":\"\",\"quickIcon\":\"\",\"types\":\"\"";
		if(null == list || list.size() <= 0){
			msg = "{\"Rows\":[{" + rootNode + ",\"orderNum\":\"0\",\"children\":[]}]}";
		} else {
			array = JSONArray.fromObject(list);
			msg = "{\"Rows\":[{" + rootNode + ",\"orderNum\":\"" + list.size() + "\", \"children\":" + array.toString() + "}]}";
		}
		return msg;
	}

	private String[] fields = { "id", "pparent_id", "text", "logic_code", "action", "showorder","icons","isQuick","quickIcon","types" };
	private String sql = "select permission_id,pparent_id,caption,logic_code,action,showorder,icons,isQuick,quickIcon,types from t_permission where pparent_id = ? order by showorder";
	private List<Map<String,Object>> getMenuByPid(List<Map<String,Object>> list) throws Exception{
		if(null == list || list.size() <= 0){
			return null;
		}
		for(Map<String,Object> map: list){
			String permission_id = String.valueOf(map.get("id"));
			List<Map<String,Object>> list1 = AccessDataBaseUtil.query4ListMap(fields, sql, new Object[] { permission_id });
			map.put("children", list1);
			map.put("orderNum", list1.size());
			this.getMenuByPid(list1);
		}
		return list;
	}
	
	
	
	/** 
	 * 描述：listTree4User 取得指定用户的权限菜单
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Jul 10, 2012  2:58:16 PM
	 * @author chun_chang
	 */
	public Object listTree4User(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String userId = jsonObject.getString("userId");
		String sql = "select PERMISSION_ID from T_USER_PERMISSION where USER_ID = ?";
		List<Object> list1 = AccessDataBaseUtil.query4List(sql, new Object[] { userId });
		Set<String> set = new HashSet<String>();
		for (Object obj : list1) {
			set.add(obj.toString());
		}

		List<Map<String, Object>> list = AccessDataBaseUtil.query4ListMap(fields1, sql2, new Object[] { "0" });
		list = this.getMenuByPid1(set, list);
		array = JSONArray.fromObject(list);
		return array.toString();
	}

	private String[] fields1 = { "id", "text" };
	private String sql2 = "select permission_id,caption from t_permission where pparent_id = ? order by showorder";
	private List<Map<String, Object>> getMenuByPid1(Set<String> set, List<Map<String, Object>> list) throws Exception {
		if (null == list || list.size() <= 0) {
			return null;
		}
		for (Map<String, Object> map : list) {
			String permission_id = String.valueOf(map.get("id"));
			boolean ischecked = set.add(permission_id);
			if (ischecked) {
				set.remove(permission_id);
			}
			List<Map<String, Object>> list1 = AccessDataBaseUtil.query4ListMap(fields1, sql2, new Object[] { permission_id });
			map.put("ischecked", !ischecked);
			map.put("children", list1);
			this.getMenuByPid1(set, list1);
		}
		return list;
	}
	
	/** 
	 * 描述：loadMenu4Left 主页-左侧菜单分类
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Jul 20, 2012  4:25:46 PM
	 * @author chun_chang
	 */
	public Object loadMenu4Left(Object jsonArray) throws Exception {
		UserBean user = (UserBean)((HttpServletRequest)this.getRequest()).getSession().getAttribute("userBean");
		String userId = user.getUserId();
		Object[] params = { "0", userId };
		//菜单
		List<Object> list2 = new ArrayList<Object>();
		List<Object> list1 = AccessDataBaseUtil.query4List(sql11, params);
		list2.addAll(list1);
		//角色
		list1 = AccessDataBaseUtil.query4List(sql12, params);
		list2.addAll(list1);
		
		//组
		list1 = AccessDataBaseUtil.query4List(sql13, params);//当前节点的菜单ID
		list2.addAll(list1);
		
		String ids = "";
		if(list2.size() > 0){
			for(Object obj: list2){
				ids += "'"+obj+"',";
			}
		}
		ids += "''";
		
		sql = "select permission_id, pparent_id, caption, logic_code, action,icons from t_permission where permission_id in ( "+ ids +") order by showorder";
		String[] field = { "id", "pid", "title", "logic_code", "url", "icons" };
		List<Map<String, Object>> list0 = AccessDataBaseUtil.query4ListMap(field, sql, null);
		this.loadMenu(list0);
		JSONArray array = JSONArray.fromObject(list0);
		return array.toString();
	}
	
	private String[] fields2 = { "id", "pid", "text", "logic_code", "url", "icon", "types" };
	private String sql11 = "select a.permission_id from t_permission a,t_user_permission b where a.permission_id = b.permission_id and a.pparent_id = ? and b.user_id = ?";
	private String sql12 = "select c.permission_id from t_permission c,t_role_permission d,t_role e,t_user_role f where c.permission_id = d.permission_id and d.role_id = e.role_id and e.role_id = f.role_id and c.pparent_id = ? and f.user_id = ?";
	private String sql13 = "select h.permission_id from t_permission h,t_role_permission i,t_role j,t_group_role k,t_group l,t_user_group m where h.permission_id = i.permission_id and i.role_id = j.role_id and j.role_id = k.role_id and k.group_id = l.group_id and l.group_id = m.group_id and h.pparent_id = ? and m.user_id = ?";
	private List<Map<String,Object>> getMenuByPid4Left(List<Map<String,Object>> list, String menuPos) throws Exception{
		if(null == list || list.size() <= 0){
			return null;
		}
		UserBean user = (UserBean)this.getRequest().getSession().getAttribute("userBean");
		
		for(Map<String,Object> map: list){
			String permission_id = String.valueOf(map.get("id"));
			Object[] params = { permission_id, user.getUserId() };
			
			//菜单
			List<Object> list2 = new ArrayList<Object>();
			List<Object> list1 = AccessDataBaseUtil.query4List(sql11, params);
			list2.addAll(list1);
			//角色
			list1 = AccessDataBaseUtil.query4List(sql12, params);
			list2.addAll(list1);
			//组
			list1 = AccessDataBaseUtil.query4List(sql13, params);
			list2.addAll(list1);
			
			String ids = "";
			if(list2.size() > 0){
				for(Object obj: list2){
					ids += "'"+obj+"',";
				}
			}
			ids += "''";
			
			sql = "select permission_id, pparent_id, caption, logic_code, action, CONCAT('ligerUI/skins/icons/',icons,'.gif'),types from t_permission where permission_id in ( "+ ids +") order by showorder";
			if("oracle".equals(user.getDbType())){
				sql = "select permission_id, pparent_id, caption, logic_code, action, 'ligerUI/skins/icons/'||icons||'.gif',types from t_permission where permission_id in ( "+ ids +") order by showorder";
			}
			List<Map<String, Object>> list0 = AccessDataBaseUtil.query4ListMap(fields2, sql, null);
			if("top".equals(menuPos)){//顶部菜单
				String icon = map.get("icon").toString();
				icon = icon.substring(20, icon.length() - 4);
				map.put("icon", icon);
				if(null == list0 || list0.size() <= 0){
					map.put("click", "");
				} else {
					map.put("children", list0);
				}
			} else {//左侧菜单
				map.put("children", list0);
			}
			
			this.getMenuByPid4Left(list0, menuPos);
		}
		return list;
	}
	
	/** 
	 * 描述：loadMenu 主页面左侧菜单-根据pid查询所有子菜单
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Jul 20, 2012  4:22:30 PM
	 * @author chun_chang
	 */
	public void loadMenu(List<Map<String, Object>> list) throws Exception {
		UserBean user = (UserBean)this.getRequest().getSession().getAttribute("userBean");
		
		for(Map<String, Object> map: list){
			String pid = map.get("id").toString();
			Object[] params = { pid, user.getUserId() };
			//菜单
			List<Object> list2 = new ArrayList<Object>();
			List<Object> list1 = AccessDataBaseUtil.query4List(sql11, params);
			list2.addAll(list1);
			//角色
			list1 = AccessDataBaseUtil.query4List(sql12, params);
			list2.addAll(list1);
			//组
			list1 = AccessDataBaseUtil.query4List(sql13, params);
			list2.addAll(list1);
			
			String ids = "";
			if(list2.size() > 0){
				for(Object obj: list2){
					ids += "'"+obj+"',";
				}
			}
			ids += "''";
			
			if("mysql".equals(user.getDbType())){
				sql = "select permission_id, pparent_id, caption, logic_code, action, CONCAT('ligerUI/skins/icons/',icons,'.gif'),types from t_permission where permission_id in ( "+ ids +") order by showorder";
			}else if("oracle".equals(user.getDbType())){
				sql = "select permission_id, pparent_id, caption, logic_code, action, 'ligerUI/skins/icons/'||icons||'.gif',types from t_permission where permission_id in ( "+ ids +") order by showorder";
			}else{
			}
			List<Map<String, Object>> list0 = AccessDataBaseUtil.query4ListMap(fields2, sql, null);
			list0 = this.getMenuByPid4Left(list0, "left");
			map.put("children", list0);
		}
		
	}

	/** 
	 * 描述：loadMenu4Left1 顶部菜单栏
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Aug 31, 2012  9:06:05 AM
	 * @author chun_chang
	 */
	public Object loadMenu4Left1(Object jsonArray) throws Exception {
		UserBean user = (UserBean)((HttpServletRequest)this.getRequest()).getSession().getAttribute("userBean");
		String userId = user.getUserId();
		Object[] params = { "0", userId };
		//菜单
		List<Object> list2 = new ArrayList<Object>();
		List<Object> list1 = AccessDataBaseUtil.query4List(sql11, params);
		list2.addAll(list1);
		//角色
		list1 = AccessDataBaseUtil.query4List(sql12, params);
		list2.addAll(list1);
		
		//组
		list1 = AccessDataBaseUtil.query4List(sql13, params);//当前节点的菜单ID
		list2.addAll(list1);
		
		String ids = "";
		if(list2.size() > 0){
			for(Object obj: list2){
				ids += "'"+obj+"',";
			}
		}
		ids += "''";
		
		sql = "select permission_id, pparent_id, caption, logic_code, action,icons from t_permission where permission_id in ( "+ ids +") order by showorder";
		String[] field = { "id", "pid", "title", "logic_code", "url", "icons" };
		List<Map<String, Object>> list0 = AccessDataBaseUtil.query4ListMap(field, sql, null);
		if(null != list0 && list0.size() > 0){
			for(Map<String, Object> map: list0){
				String pid = map.get("id").toString();
				List<Map<String, Object>> list = this.loadMenu4Top(pid, userId);
				
				Map<String, Object> map1 = new HashMap<String, Object>();
				map1.put("width", _width);
				map1.put("items", list);
				map.put("items", map1);
			}
		}
		JSONArray array = JSONArray.fromObject(list0);
		return array.toString();
	}
	
	/** 
	 * 描述：loadMenu4Top 顶部菜单
	 * @param pid
	 * @param userId
	 * @return
	 * @CreateOn Aug 31, 2012  9:22:52 AM
	 * @author chun_chang
	 * @throws Exception 
	 */
	public List<Map<String, Object>> loadMenu4Top(String pid, String userId) throws Exception{
		Object[] params = { pid, userId };
		//菜单
		List<Object> list2 = new ArrayList<Object>();
		List<Object> list1 = AccessDataBaseUtil.query4List(sql11, params);
		list2.addAll(list1);
		//角色
		list1 = AccessDataBaseUtil.query4List(sql12, params);
		list2.addAll(list1);
		//组
		list1 = AccessDataBaseUtil.query4List(sql13, params);
		list2.addAll(list1);
		
		String ids = "";
		if(list2.size() > 0) {
			for(Object obj: list2) {
				ids += "'" + obj + "',";
			}
		}
		ids += "''";
		
		sql = "select permission_id, pparent_id, caption, logic_code, action, CONCAT('ligerUI/skins/icons/',icons,'.gif'),types from t_permission where permission_id in ( "+ ids +") order by showorder";
		List<Map<String, Object>> list0 = AccessDataBaseUtil.query4ListMap(fields2, sql, null);
		
		list0 = this.getMenuByPid4Left(list0, "top");
		return list0;
	}
	
	/** 
	 * 描述：menuTree 角色选菜单时，菜单树
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Jul 10, 2012  5:17:34 PM
	 * @author chun_chang
	 */
	public Object listTree4Role(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String id = jsonObject.getString("roleId");
		String sql = "select PERMISSION_ID from T_ROLE_PERMISSION where ROLE_ID = ?";
		List<Object> list1 = AccessDataBaseUtil.query4List(sql, new Object[] { id });
		Set<String> set = new HashSet<String>();
		for (Object obj : list1) {
			set.add(obj.toString());
		}

		List<Map<String, Object>> list = AccessDataBaseUtil.query4ListMap(fields1, sql2, new Object[] { "0" });
		list = this.getMenuByPid1(set, list);
		array = JSONArray.fromObject(list);
		return array.toString();
	}
	
	
	@Override
	public Object insert(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		Object[] obj = new Object[fields.length];
		for (int j = 1; j < fields.length; j++) {
			obj[j] = jsonObject.getString(fields[j]);
		}
		obj[0] = AccessDataBaseUtil.getPKUUID();
		String sql = "select count(*) from t_permission where pparent_id = ? and caption = ?";
		int cnt = AccessDataBaseUtil.queryForInt(sql, new Object[]{ obj[1], obj[2] });
		if(cnt > 0){
			return "{\"result\":false,\"resultmessage\":\"调用失败\",\"resultrecord\":\"名称重复\"}";
		}
		
		sql = "insert into t_permission(permission_id,pparent_id,caption,logic_code,action,showorder,icons,isQuick,quickIcon,types) values(?,?,?,?,?,?,?,?,?,?)";
		AccessDataBaseUtil.executeSQLUpdate(sql, obj);
		return "{\"result\":true,\"resultmessage\":\"调用成功\",\"resultrecord\":\"新建成功\"}";
	}

	@Override
	public Object update(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		Object[] obj = new Object[fields.length];
		for (int j = 0; j < fields.length - 1; j++) {
			obj[j] = jsonObject.getString(fields[j+1]);
		}
		obj[obj.length - 1] = jsonObject.getString(fields[0]);
		
		String sql = "select count(*) from t_permission where pparent_id = ? and permission_id <> ? and caption = ?";
		int cnt = AccessDataBaseUtil.queryForInt(sql, new Object[]{ obj[0], obj[obj.length - 1], obj[1] });
		if(cnt > 0){
			return "{\"result\":false,\"resultmessage\":\"调用失败\",\"resultrecord\":\"名称重复\"}";
		}
		
		List<String> list = new ArrayList<String>();
		sql = "update t_permission set pparent_id = '" + obj[0] + "',caption = '" + obj[1] + "',logic_code = '"
			+ obj[2] + "',action = '" + obj[3] + "',showorder = " + obj[4] + ",icons = '" + obj[5]
			+ "',isQuick = '" + obj[6] + "',quickIcon = '" + obj[7] + "',types = '" + obj[8]
			+ "' where permission_id = '" + obj[9] + "'";
		list.add(sql);
		
		if("N".equals(obj[6].toString())){
			String sql2 = "delete from t_desktop where permission_id = '" + obj[9] + "'";
			list.add(sql2);
		}
		
		AccessDataBaseUtil.executeSQLUpdate(list);
		return "{\"result\":true,\"resultmessage\":\"调用成功\",\"resultrecord\":\"修改成功\"}";
	}

	@Override
	public Object updateBatch(Object jsonArray) throws Exception {
		return null;
	}

	@Override
	public Object delete(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String id = jsonObject.getString("ids");
		String[] ids = id.split(",");
		List<Object> list = new ArrayList<Object>();
		for(String id1: ids){
			list.add(id1);
		}
		List<Object> list1 = this.getMenuIdsByPids(list);
		list1.addAll(list);
		
		StringBuffer sql = new StringBuffer("delete from t_permission where permission_id in ('");
		StringBuffer sql1 = new StringBuffer("delete from t_user_permission where permission_id in ('");
		StringBuffer sql2 = new StringBuffer("delete from t_role_permission where permission_id in ('");
		
		for(Object id2: list1){
			sql.append(id2).append("','");
			sql1.append(id2).append("','");
			sql2.append(id2).append("','");
		}
		
		sql.delete(sql.length() - 3, sql.length() - 1).append(")");
		sql1.delete(sql1.length() - 3, sql1.length() - 1).append(")");
		sql2.delete(sql2.length() - 3, sql2.length() - 1).append(")");
		
		String[] sqls = { sql1.toString(), sql2.toString(), sql.toString() };
		AccessDataBaseUtil.executeSQLUpdate(sqls);
		return "\"删除成功\"";
	}
	private String sql1 = "select permission_id from t_permission where pparent_id = ?";
	private List<Object> getMenuIdsByPids(List<Object> list) throws Exception{
		if(null == list || list.size() <= 0){
			return null;
		}
		List<Object> list2 = new ArrayList<Object>();
		for(Object obj: list){
			List<Object> list1 = AccessDataBaseUtil.query4List(sql1, new Object[] { obj });
			if(null != list1 && list1.size() > 0){
				List<Object> list3 = this.getMenuIdsByPids(list1);
				list2.addAll(list1);
				list2.addAll(list3);
			}
		}
		return list2;
	}
	
	
	
	@Override
	public Object recordCount(Object jsonArray) throws Exception {
		return null;
	}

	@Override
	public Object setRequest(HttpServletRequest request) throws Exception {
		this.request = request;
		return request;
	}
	
}
